package com.kinghunt.misp.common.utils;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author: jinping
 * @desc: 用户token格式：token= BASE64_PREFIX + "_" + userId
 * @date 2019/6/28
 * @modified by:
 */
public class TokenUtils {
    private static final String BASE64_PREFIX = "anhtc2xzaW9kamZwd2UwMQ==";
    private static final String TOKEN_DELIMITER = "_";

    /**
     * token= BASE64_PREFIX + "_" + userId
     */
    public static long toUserId(String token) {
        long userId;
        try {
            byte[] base64decodedBytes = Base64.getDecoder().decode(token);
            String originalToken = new String(base64decodedBytes, StandardCharsets.UTF_8);
            userId = Long.parseLong(originalToken.substring(originalToken.indexOf(TOKEN_DELIMITER) + 1));
        } catch (Exception e) {
            return 0;
        }
        return userId;
    }

    public static String toToken(long userId) {
        String originalToken = BASE64_PREFIX + "_" + userId;
        return Base64.getEncoder().encodeToString(originalToken.getBytes(StandardCharsets.UTF_8));
    }
}
